<?php
function validateUsername($name1){
	//NO cumple longitud minima
	if(strlen($name1) < 1)
		return false;
	//SI longitud pero NO solo caracteres A-z
	else if(!preg_match("/^[a-zA-Z]+$/", $name1))
		return false;
	// SI longitud, SI caracteres A-z
	else
		return true;
}

function validateEmail($email1){
	//NO hay nada escrito
	if(strlen($email1) == 0)
		return false;
	// SI escrito, NO VALIDO email
	else if(!filter_var($email1, FILTER_VALIDATE_EMAIL))
		return false;
	// SI rellenado, SI email valido
	else
		return true;
}


//guardamos las variables del formulario
$name          = $_POST['nombre'];
$firstSurname  = $_POST['apellido1'];
$secondSurname = $_POST['apellido2'];
$email         = $_POST['email'];
$id        = $_POST['id'];
include "conexion.php";

$query1="select * from member where member_email='$email'";
$result1=mysql_query($query1);
include "cerrar_conexion.php";
if(mysql_num_rows($result1)>=2)
{
	?>
	   	 <head> 
	    	<script>
            	window.alert("This email already exist");
                history.back();
            </script>
	    </head> 
    	<?php
}

	if(!validateUsername($name))
		$name = "error";
	if(!validateUsername($firstSurname))
		$firstSurname = "error";
	if(!validateUsername($secondSurname))
		$secondSurname = "error";
	if(!validateEmail($email))
		$email = "error";


	//Comprobamos si todo ha ido bien
	if($name != "error" && $firstSurname != "error" && $secondSurname != "error" && $email != "error"){
		include "conexion.php";


		$query ="UPDATE member set member_email='$email', member_name='$name', member_surname1='$firstSurname', member_surname2='$secondSurname' WHERE idMember='$id'";
		mysql_query($query) or die("Error en la consulta SQL");
		include "cerrar_conexion.php";
		header('Location: http://localhost/grupo5/Listofemployees.php');
	}else{
		 ?> 
	   	 <head> 
	    	<script>
            	window.alert("Complete all fields correctly");
                history.back();
            </script>
	    </head> 
    	<?php
		
	}
?>